const app = getApp()
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    casArray: null,
    schoolId: 0,
    num: null
  },
  onLoad: function() {
    var that = this;
    app.getOpenId().then(function(res) {

      wx.request({
        url: 'http://xxxxxxx:8080/webchat/login/queryallschool',
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          console.log(res.data)
          //从数据库获取用户信息
          that.setData({
            casArray: res.data.data.messages
          })
        }
      })
      //从数据库获取用户信息
      that.queryUsreInfo();
      // if (app.globalData.userInfo != null) {
      //   wx.switchTab({
      //     url: '../index/index',
      //   })
      // }






    })

  },

  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      //插入登录的用户的相关信息到数据库
      wx.request({
        url: 'http://xxxxxx .198:8080/webchat/login/adduser',
        data: {
          openId: app.globalData.openId,
          nickName: e.detail.userInfo.nickName,
          avatarUrl: e.detail.userInfo.avatarUrl,
          province: e.detail.userInfo.province,
          city: e.detail.userInfo.city,
          country: e.detail.userInfo.country,
          gender: e.detail.userInfo.gender,
          schoolId: that.data.schoolId,
          studentNumber: that.data.num
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'POST',
        success: res => {
          //从数据库获取用户信息
          that.queryUsreInfo();
        }
      });
      //授权成功后，跳转进入小程序首页
      // wx.switchTab({
      //   url: '../index/index',
      // })
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  //获取用户信息接口
  queryUsreInfo: function() {
    wx.request({
      url: 'http://xxxxx:8080/webchat/login/queryuser',
      data: {
        openId: app.globalData.openId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log(res.data);
        app.globalData.userInfo = res.data.data.userInfo;
        if (res.data.data.userInfo != null) {
          wx.switchTab({
            url: '../index/index',
          })
        }

      }
    });
  },
  bindCasPickerChange: function(e) {
    console.log(e)
    var that = this;
    that.setData({

      casId: e.detail.value,
      schoolId: that.data.casArray[e.detail.value].schoolId
    })
  },
  formSubmit: function(e) {
    this.data.num = e.detail.value.num;
  }
})